import os
import time
from fastapi import APIRouter, File, UploadFile
from pydantic import BaseModel
from MySQL import MySql

db = MySql()
# D:/md/
# /usr/share/nginx/html/skin/md/
MAIN_POSTITION = '/usr/share/nginx/html/skin/md/'
FILE_MAIN = '/usr/share/nginx/html/skin/md/'
TABLE_NAME = 'notes'

router = APIRouter(
    prefix="/notes",
    tags=['笔记']
)


def line_keywords(line, keywords):
    key_index = []
    start = line.find(keywords)
    while start != -1:
        key_index.append(start + 1)
        start = line.find(keywords, start + 1)
    return key_index


def file_keywords(filename, keywords):
    if os.path.exists(MAIN_POSTITION + filename):
        f = open(MAIN_POSTITION + filename, 'r', encoding='utf8')
        line = 0
        dict_keywords = dict()

        for each_line in f:
            line += 1

            if keywords in each_line:
                key_index = line_keywords(each_line, keywords)
                dict_keywords[line] = key_index
        f.close()
        return dict_keywords
    else:
        return dict()


def file_search(keyword='', list_data=[]):
    # os.getcwd()  当前目录
    md_list = list_data
    result_list = []
    for file in md_list:
        if file_keywords(file['position'], keyword):
            # /usr/share/nginx/html
            result_list.append(file)
    return result_list


class NotesList(BaseModel):
    # 默认值写法
    keyword: str = ''


# 获取笔记列表
@router.post('/get_notes_list')
def get_notes_list(item: NotesList):
    """
    获取笔记列表\n
        参数1:keyword 搜索的名称
    """
    data = db.execute('select * from notes;')
    columns = db.execute('show columns from notes;')
    list_data = []
    for val in data:
        dict_list = dict()
        key = 0
        for column in columns:
            dict_list[column[0]] = val[key]
            key += 1
        list_data.append(dict_list)
    return {
        "code": 0,
        "data": file_search(item.keyword, list_data),
        "message": "获取成功"
    }


class GetNotes(BaseModel):
    id: int = 1


def open_md(list_data=[]):
    list_return = []
    for item in list_data:
        dict_list = dict()
        with open(MAIN_POSTITION + item['position'], mode='r', encoding='utf-8') as f:
            dict_list['name'] = item['title']
            dict_list['data'] = f.read()
            db.execute('update %s set browse=%d where id=%d' % (TABLE_NAME, item['browse'] + 1, item['id']))
            list_return.append(dict_list)
    return list_return


# 笔记详情
@router.post('/get_notes')
def get_notes(item: GetNotes):
    """
    获取某一个笔记\n
        参数1:id 笔记id
    """
    data = db.execute('select * from notes where id=%d;' % item.id)
    columns = db.execute('show columns from notes;')
    list_data = []
    for val in data:
        dict_list = dict()
        key = 0
        for column in columns:
            dict_list[column[0]] = val[key]
            key += 1
        list_data.append(dict_list)
    return {
        "code": 0,
        "data": open_md(list_data),
        "message": "获取成功"
    }




# 上传笔记
@router.post('/upload_note')
async def upload_note(title:str = File(default=None),message:str = File(default=None),file: UploadFile = File(default=None)):
    try:
        res = await file.read()
        max_id = db.execute('select max(id) from notes')[0][0]
        # with open(FILE_MAIN + file.filename, "w") as f:
        #     f.write(res)
        db.execute('insert into %s(id,title,message,browse,date,position) values (%d,%s,%s,%s)' % (TABLE_NAME,max_id,title,message,time.time(),filename))
        return {"message": "success", 'time': time.time(), 'filename': file.filename}
    except Exception as e:
        return {"message": str(e), 'time': time.time(), 'filename': file.filename}
